package com.util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Data
@Configuration
public class JwtUtil {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 签名私钥
    private String key = "yVrGQC0OHQHmov^ioFraw*#$EkuzPN6&BgG!HRt4X9YsB45wOZ";

    // 签名的失效时间
    private Long ttl = 360000L;

    // Redis用户Token失效时间
    private Long redisTtl = 3600L * 14 * 24;

    /**
     * 设置认证token
     * id:登录用户id
     * subject：登录用户名
     */
    public String createJwt(String id, String name, Map<String, Object> map) {
        // 创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);
        //根据map设置claims
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                jwtBuilder.claim(entry.getKey(), entry.getValue());
            }
            jwtBuilder.setExpiration(new Date(System.currentTimeMillis() + ttl));
        }

        String token = jwtBuilder.compact();

        stringRedisTemplate.boundValueOps(token).set(token, redisTtl, TimeUnit.SECONDS);
        return token;
    }

    //不管是否过期，都返回claims对象
    public Claims parseJwt(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key) // 设置标识名
                    .parseClaimsJws(token)  //解析token
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }
}
